<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Team. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/docs
 */


class informationController extends appRain_Base_Core
{
    /* Controller Name */
    public $name = 'Information';

    /**
     * A restricted index page
     * This function is hidden 
     * from browser action 
     *
     * @return null
     */
    private function index( $msg = NULL)
    {
    }

    /**
     * Manage all information set
     *
     * $parameter type string
     * $parameter action string
     * $parameter id integer
     * $parameter page  integer
     * @return null
     */
    public function manageAction( $type = NULL , $action = NULL, $id = NULL, $page = NULL )
    {
        /**
         * - Read Information Set defination 
         * - Set admin TAB and check login Authentication
         */
        $definition = app::__def()->getInformationSetDefinition($type);
        $this->setAdminTab($definition['base']['admin_tab']);

        /* Current user id to keep trac data profiling */
        $current_user_id    = $this->getUserStatusId();
        $this->page_title   = $definition['base']['title'];

        /* Set addons */
        $definition['base']['addons']   = isset($definition['base']['addons'])?$definition['base']['addons']:Array();
        $this->addons                   = array_merge($definition['base']['addons'],array('validation','rich_text_editor','row_manager'));
        $errors                         = Array();

         /* Save  Information Set */
        if( isset( $this->data['Information']))
        {
            /* Set user id */
            $this->data['Information']['fkey'] = $current_user_id;

            /* Formate data from in a proper way */
            $this->data = $this->format_data($type,$this->data,$id);


            /* Run call backfunction before saving Information Set */
            $this->_before_information_set_save(array("type"=>"$type"));

            /* Save Information Set */
            $InfoSetObj = App::InformationSet($type)->save_information($this->data);

            /* Call back after saving Information Set */
            $this->_after_information_set_save(
                array(
                        "type"  => "$type",
                        "id"    => $InfoSetObj->getId()
                )
            );

            $errors = $InfoSetObj->getErrorInfo();

            if(empty($errors)) {
                /* Page to redirect */
                $page = ( $this->data['Information']['page'] !='' ) 
                        ? '?page=' . $this->data['Information']['page'] : '';
                
                App::Module('Notification')->Push("Updated successfully.");

                /* Redirect to user control */
                if(isset($this->post['Button']['button_save_and_update'])) {
                    $this->redirect('/information/manage/' . $type . '/update/' . $InfoSetObj->getId()  );
                }
                else if( isset($this->post['Button']['button_save_and_add'])) {
                    $this->redirect('/information/manage/' . $type . '/add'  );
                }
                else {
                    $this->redirect('/information/manage/' . $type . $page );
                }
                exit;
            }
        }

        /* Information Set Search module */
        $src_key    = ''; 
        $src_field  = '';
        $src_cat    = '';
        
        if (isset($id)) {
            $this->_on_information_set_view(
                array(
                    "type"  => "$type",
                    "id"    => $id
                )
             );
             
            $data = App::InformationSet($type)->findById($id);
        }
        else
        {
            /* Formate search data */
            if (isset($this->data['Search']['category'])){
                $src_category           = $this->data['Search']['category'];
                $session_arr['src_cat'] = $src_category;
            }

            if (isset($this->data['Search']['src_key']) 
                && isset($this->data['Search']['field'])
            ) {
                $session_arr['src_key'] = $this->data['Search']['src_key'];
                $session_arr['src_field'] =$this->data['Search']['field'];
            }

            /**
             * Save session for a user 
             * friendly search 
             */
            if (!empty($session_arr)) {
                App::Load("Module/Session")->write($type,$session_arr);
            }

            /* Read previouse search query */
            $src_info = App::Load("Module/Session")->read($type);

            /* Formate the search query */
            $src_cat = isset($src_info['src_cat']) 
                       ? $src_info['src_cat'] : '';
            $c2 = array();
            
            if ($src_cat != ''){
                $src_cat_info = explode('|',$src_cat);
                $c2[] = "ioption='" . $src_cat_info[0] . "' and ivalue like '%" . $src_cat_info[1] . "%'";
            }
            
            $src_key    = isset($src_info['src_key'])
                          ? $src_info['src_key'] :  "";
            $src_field  = isset($src_info['src_field'])
                          ? $src_info['src_field'] : "";
            
            if (($src_key != '') && ($src_field != '')){
                if (!empty($c2)) {
                    $c2[] = "AND";
                }
                $c2[] = "ioption='$src_field' and ivalue like '%$src_key%'";
            }

            /* Read data from database */
            $order = isset($this->information_defination[$type]['extended']['order']) 
                     ? $this->information_defination[$type]['extended']['order'] : "ORDER BY Information.id DESC";
            
            /**
             * Fetch the Information Set Data
             * with default pagination
             */
            $data = App::informationSet($type)
                    ->Listing(
                        array(
                            "c1" => $order,
                            "c2"=>$c2,
                            "pagination" => "Yes",
                            "limit" => $this->get_config('default_pagination')
                        )
                    );
        }

        /* Count total entry */
        $entry_total =  App::Model('Information')
                        ->countentry(
                            isset($current_user_id)
                            ? ("type='$type' AND fkey = $current_user_id") : ("type='$type'") 
                        );

        /* Set some variables to output */
        $this->set('src_key', $src_key);
        $this->set('src_field', $src_field);
        $this->set('src_cat', $src_cat);
        $this->set('data_list', $data);
        $this->set('type', $type);
        $this->set('page', $page);
        $this->set('action', $action);
        $this->set('current_user_id', $current_user_id);
        $this->set('definition', $definition);
        $this->set('errors', $errors);
        $this->set('entry_total', $entry_total);
    }

    /**
     * Formate post data to save Information Set
     *
     * $parameter type string
     * $parameter formated_data array
     * $parameter id integer
     * @return array
     */
    private function format_data( $type = NULL, $formated_data = NULL, $id = NULL)
    {
        $definition = app::__def()->getInformationSetDefinition($type);

        foreach( $definition['fields'] as $field => $def){
            switch($def["type"]){
            
                /* Formate fileTag data */
                case "fileTag" :
                    
                    $path = $this->get_config("filemanager_path") . "/";
                    
                    if (isset($formated_data["Information"]["id"])){
                        $previouse_info = App::informationSet()->findById( $formated_data["Information"]["id"] );
                    }

                    $previouse_file = isset($previouse_info[$field]) 
                                      ? $previouse_info[$field] : "";

                    if( $formated_data["Option"][$field]["name"] != ""){
                    
                        /* Clear garbaze file from disc */
                        if ((file_exists( $path . $previouse_file)) 
                            && ($previouse_file != "")
                        ){
                            @unlink( $path . $previouse_file );
                        }

                        /* Upload files */
                        $file_data = App::Load("Helper/Utility")->upload($formated_data["Option"][$field],$path);

                        /* Resize the if the file an image */
                        if( App::Load("Helper/Utility")->is_image($file_data["file_name"])){
                            $w = isset($def["parameters"]["maxwidth"]) ? $def["parameters"]["maxwidth"] : NULL;
                            $h = isset($def["parameters"]["maxheight"]) ? $def["parameters"]["maxheight"] : NULL;

                            if( isset($w) || isset($h)){
                                $np = $path . "/" . $file_data["file_name"];
                                App::Load("Helper/Utility")->createThumb($np,$np,$w,$h);
                            }
                        }
                        $formated_data["Option"][$field] = $file_data["file_name"];
                    }
                    else {
                        $formated_data["Option"][$field] = $previouse_file;
                    }
                    break;
                    
            }
        }
        
        /* Return Formated Data */
        return $formated_data;
    }

    /**
     * Export Information Set Data
     */
    public function exportAction($type = NULL)
    {
        /* Export and Download Data */
        App::InformationSet($type)
            ->setExporttype($this->data['Export']['type'])
            ->export(true);
    }
}
